package com.example.demo.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

@RestController
public class TestWebSocketController extends TextWebSocketHandler {

    @Autowired
    private static Logger log = LoggerFactory.getLogger(TestWebSocketController.class);

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        //在服务端和客户端成功连接后自动调用
        log.info("客户端服务端连接成功");
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        //服务端收到消息后自动调用 message变量就是服务端收到的消息
        log.info("服务端收到客户端发来的消息" + message.toString());

        session.sendMessage(message); //session 是个会话,里面记录了通信双方是谁
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        //客户端服务端连接出现异常后自动调用 exception就是收到的异常
        log.warn("服务端和客户端连接出现异常");
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        //连接正常关闭后,自动调用的
        log.info("服务端客户端连接正常关闭");
    }
}
